﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AzureDiagMon.Common.Helpers
{
    public class WpfHelper
    {
        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        public static IEnumerable<DependencyObject> FindVisualChildren(DependencyObject depObj, params Type[] types)
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && (types.Length == 0 ||
                        types.Contains(child.GetType())))
                    {
                        yield return child;
                    }

                    foreach (DependencyObject childOfChild in FindVisualChildren(child, types))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        public static void FocusFirstChildInputElement(DependencyObject childControl)
        {
            var focusableTypes = new[] { typeof (TextBox), typeof (RichTextBox), typeof (CheckBox),
                                         typeof (ComboBox), typeof (ListBox), typeof (RadioButton),
                                         typeof (DatePicker), typeof (PasswordBox), typeof (Slider),
                                         typeof (TextBox), typeof (TextBox),
                                     };
            var firstControl = FindVisualChildren(childControl, focusableTypes).FirstOrDefault();
            Keyboard.Focus(firstControl as Control);            
        }
    }
}
